package com.infolab.aims.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.infolab.aims.GlobalConstant;
import com.infolab.aims.domain.SystemUser;

public class ExecuteTimeInterceptor extends HandlerInterceptorAdapter{
 
	private static final Logger logger = Logger.getLogger(ExecuteTimeInterceptor.class);
 
	//before the actual handler will be executed
	public boolean preHandle(HttpServletRequest request, 
		HttpServletResponse response, Object handler)
	    throws Exception {
 
		long startTime = System.currentTimeMillis();
		request.setAttribute("startTime", startTime);
 
		return true;
	}
 
	//after the handler is executed
	public void postHandle(
		HttpServletRequest request, HttpServletResponse response, 
		Object handler, ModelAndView modelAndView)
		throws Exception {
 
		long startTime = (Long)request.getAttribute("startTime");
 
		long endTime = System.currentTimeMillis();
 
		long executeTime = endTime - startTime;
 
		if(modelAndView!=null)
			modelAndView.addObject("executeTime",executeTime);
 
		SystemUser systemUser = (SystemUser) request.getSession().getAttribute(GlobalConstant.SESSION_CURRENT_SYSTEMUSER);
		
		String username="unknown";
		if(systemUser!=null)
			username=systemUser.getUserName();
		
		
		//log it
		if(logger.isDebugEnabled()){
		   logger.debug("[" + request.getRequestURI()+" "+request.getMethod() + "], user : "+username+", remote ip : "+request.getRemoteAddr()+" executeTime : " + executeTime + "ms");
		}
		if(executeTime>30000)
			logger.warn("[" + request.getRequestURI()+" "+request.getMethod() + "], user : "+username+", remote ip : "+request.getRemoteAddr()+"  [SLOW] executeTime : " + executeTime + "ms");
		else if(executeTime>60000)
			logger.warn("[" + request.getRequestURI()+" "+request.getMethod() + "], user : "+username+", remote ip : "+request.getRemoteAddr()+"  [SUPERSLOW] executeTime : " + executeTime + "ms");
		else if(executeTime>120000)
			logger.warn("[" + request.getRequestURI()+" "+request.getMethod() + "], user : "+username+", remote ip : "+request.getRemoteAddr()+"  [MEGASLOW] executeTime : " + executeTime + "ms");
	}
}